import { web3Accounts, web3Enable, web3FromAddress } from "@polkadot/extension-dapp";
import { Modal, message } from "antd";
import store from "../utils/store";
import { formatAddress } from "../utils/formatter";
import { init, signMessage } from "./oss";
import { loginRandomString, userLoginByWallet } from "./graphql";
import { loading } from "../utils/antd-helper";
const { ApiPromise, WsProvider, Keyring } = require("@polkadot/api");

export function getAccountId() {
	return new Promise(async (resolve, reject) => {
		console.log("loginByExtension");
		loading("Loading");
		const allInjected = await web3Enable("cess dapp");
		console.log("allInjected", allInjected);
		let accounts = await web3Accounts();
		console.log("accounts", accounts);
		if (!accounts || accounts.length == 0) {
			loading();
			message.error("Install polkadot wallet extension please.", 5000, function () {
				resolve(null);
				window.open("https://polkadot.js.org/extension/");
			});
		}
		for (let acc of accounts) {
			acc.address = formatAccountId(acc.address);
      console.log(acc.address);
		}
		loading();
		if (accounts.length == 1) {
			store.set("addr", accounts[0].address);
			store.set("account", accounts[0]);
			return resolve(accounts[0].address);
		}
		let addr = store.get("addr");
		if (addr) {
			let acc = accounts.find(t => t.address == addr);
			if (acc) {
				acc.curr = true;
			}
		}
		Modal.info({
			title: "Select account",
			footer: null,
			content: (
				<div className="account-select-box">
					{accounts.map(t => {
						return (
							<div
								className={t.curr ? "fa fa-home curr" : "fa fa-home"}
								key={t.address}
								onClick={() => {
									store.set("addr", t.address);
									store.set("account", t);
									resolve(t.address);
									Modal.destroyAll();
								}}>
								<span>{t.meta.name}</span>
								<label>{formatAddress(t.address)}</label>
							</div>
						);
					})}
				</div>
			)
		});
	});
}
export async function loginByExtension() {
	let acc = await getAccountId();
	loading("Loading");
	let randomStr = await loginRandomString(acc);
	loading();
	if (!randomStr) {
		return { msg: "error" };
	}
	loading("Loading");
	let sign = await signMessage(acc, randomStr);
	let ret = await userLoginByWallet(acc, sign);
	loading();
	if (ret.msg != "ok") {
		return ret;
	}
	return ret;
}
export async function hasExtension() {
	const extensions = await web3Enable("cess dapp");
	return extensions.length > 0;
}
export function formatAccountId(accountId32) {
	if (!accountId32 || accountId32.length == 64) {
		return accountId32;
	}
  const keyring = new Keyring({ type: "sr25519", ss58Format: 42 });
	const pair = keyring.addFromAddress(accountId32);
	keyring.setSS58Format(11330);
	return pair.address;
}
export function logout() {
	store.remove("addr");
	store.remove("account");
}
